package astudy.thread;


public class Channel<T> {

	private int start;
	private int end;
	private T[] array;
	
	public Channel(T[] array) {

		this.start = 0;
		this.end = 1;
		this.array = array;
	}
	
	public boolean put(T a) {
		if ((this.end+1)%this.array.length == this.start) {
			return false;
		} else {
			synchronized(this) {
				this.array[this.end] = a;
				System.out.println("==============" + Thread.currentThread().getName() + " put a[" + this.end + "]=" + a);
//				sleep(50);
				this.end = (this.end+1)%this.array.length;
				return true;
			}
		}
	}
	
	public T get() {
		if ((this.start+1)%this.array.length == this.end) {
			return null;
		} else {
			synchronized(this) {
				this.start = (this.start+1)%this.array.length;
				T a = this.array[this.start];
				System.out.println(Thread.currentThread().getName() + " get a[" + this.start + "]=" + a);
				return a;
			}
		}
	}
	
//	private void sleep(long m) {
//		try {
//			Thread.sleep(m);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
}
